//action types
import { CATALOG_FETCH_CATEGORY, CATALOG_FETCH_SUB_CATEGORY, ASYNC_STATUS } from "../action-types";

//api
import api from "../api/api"

/**
 *  Request
 */
const fetchCategoryRequest = () => {
  return {
    type: CATALOG_FETCH_CATEGORY,
    status: ASYNC_STATUS.LOADING
  }
}

/**
 *  Success
 */
export function fetchCategorySuccess(data) {
  return {
    type: CATALOG_FETCH_CATEGORY,
    status: ASYNC_STATUS.SUCCESS,
    data: data
  }
}

/**
 *  Failure
 */
export function fetchCategoryFailure() {
  return {
    type: CATALOG_FETCH_CATEGORY,
    status: ASYNC_STATUS.ERROR
  }
}

/**
 * do
 */
export function fetchCategoryData(parentId) {
  let data = (parentId == undefined) ? null : {parentId: parentId}

  return dispatch => {
    dispatch(fetchCategoryRequest())

    api.getCategoryData({
      data: data,
      success: (res) => {
        console.log(res)
        if (res.success == true) {
          console.log(res.data)
          dispatch(fetchCategorySuccess(res.data))
        } else {
          dispatch(fetchCategoryFailure())
        }
      }
    })
  }
}

module.exports = {
  fetchCategoryRequest,
  fetchCategorySuccess,
  fetchCategoryFailure,
  fetchCategoryData
}